package com.tebiecloud.yunst.server.controller.feign;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.*;
import com.tebiecloud.yunst.client.constants.ResultEnum;
import com.tebiecloud.yunst.client.model.entity.YunBank;
import com.tebiecloud.yunst.client.model.entity.YunBankCard;
import com.tebiecloud.yunst.client.model.entity.YunBankType;
import com.tebiecloud.yunst.client.model.entity.YunStUser;
import com.tebiecloud.yunst.client.model.vo.BandCardVO;
import com.tebiecloud.yunst.client.service.IYunStBankCardServiceClient;
import com.tebiecloud.yunst.server.service.YunBankCardService;
import com.tebiecloud.yunst.server.service.YunBankService;
import com.tebiecloud.yunst.server.service.YunBankTypeService;
import com.tebiecloud.yunst.server.service.YunStUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/feign/bank")
public class BankCardController implements IYunStBankCardServiceClient {

    @Value("${tebiecloud.yunst.validateAndCacheCardInfo}")
    private String validateAndCacheCardInfo;

    @Autowired
    private YunBankCardService yunBankCardService;

    @Autowired
    private YunBankTypeService yunBankTypeService;

    @Autowired
    private YunBankService yunBankService;

    @Autowired
    private YunStUserService yunStUserService;

    @PostMapping("applyBindBankCard")
    @Override
    public ResultBody<BandCardVO> applyBindBankCard(@RequestParam(value = "userId") Long userId, @RequestParam(value = "phone")String phone,
                                                    @RequestParam(value = "cardNo")String cardNo, @RequestParam(value = "name")String name,
                                                    @RequestParam(value = "identityNo")String identityNo,@RequestParam(value = "openId")String openId){
        BandCardVO bandCardVO = new BandCardVO();
        Integer isBindCard = 0;//该卡是否已经绑定
        //查询是否有此用户
        QueryWrapper<YunStUser> yunStUserQueryWrapper = new QueryWrapper<>();
        yunStUserQueryWrapper.eq("user_id",userId);
        YunStUser yunStUser = yunStUserService.getOne(yunStUserQueryWrapper);
        if(yunStUser==null){
            //创建新用户
            Map<String,Object> map = yunStUserService.createOrUpdate(userId,"weChatPublic",openId);
            if(map.get("status").equals("error")){
                return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_CREATE_ERROR.getCode(),map.get("message").toString());
            }else{
                yunStUser = (YunStUser) map.get("yunStUser");
            }
        }
        //检查所有绑定卡的记录
        QueryWrapper<YunBankCard> yunBankCardQueryWrapper = new QueryWrapper<>();
        yunBankCardQueryWrapper.eq("biz_user_id",yunStUser.getBizUserId());
        List<YunBankCard> yunBankCardList = yunBankCardService.list(yunBankCardQueryWrapper);
        for(YunBankCard yunBankCard:yunBankCardList){
            if(yunBankCard.getCardNo().equals(cardNo)){
                YunBankCard yunBankCard1 = new YunBankCard();
                yunBankCard1.setStatus(1);
                UpdateWrapper<YunBankCard> yunBankCardUpdateWrapper = new UpdateWrapper<YunBankCard>();
                yunBankCardQueryWrapper.eq("card_no",yunBankCard.getCardNo());
                yunBankCardService.update(yunBankCard1,yunBankCardQueryWrapper);
                isBindCard = 1;
            }else{
                YunBankCard yunBankCard1 = new YunBankCard();
                yunBankCard1.setStatus(0);
                UpdateWrapper<YunBankCard> yunBankCardUpdateWrapper = new UpdateWrapper<>();
                yunBankCardQueryWrapper.eq("card_no",yunBankCard.getCardNo());
                yunBankCardService.update(yunBankCard1,yunBankCardQueryWrapper);
            }
            //使用原来的身份证和姓名
            name = yunBankCard.getName();
            identityNo = yunBankCard.getIdentityNo();
        }
        if(isBindCard.equals(1)){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_CARD_EXIT.getCode(), ResultEnum.YUN_ST_CARD_EXIT.getMessage());
        }

        //校验身份证是否正确
        if(!IdentityNoUtils.isIdentityNo(identityNo)){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_IDENTITYNO_ERROR.getCode(), ResultEnum.YUN_ST_USER_IDENTITYNO_ERROR.getMessage());
        }
        //如果没有实名继续实名
        if(StringUtils.isEmpty(yunStUser.getIdentityNo())){
            YunStUser yunStUser1 = new YunStUser();
            yunStUser1.setBizUserId(yunStUser.getBizUserId());
            yunStUser1.setName(name);
            yunStUser1.setIdentityNo(identityNo);
            Map<String,String> realNameResult = yunStUserService.realName(yunStUser1);
            if(realNameResult.get("status").equals("error")){
                return ResultBodyUtils.build(Integer.valueOf(realNameResult.get("code")), realNameResult.get("message"));
            }
        }
        Map<String, Object> resultMap = getCardNoInfo(cardNo);
        if(resultMap.get("status").equals("error")){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_BANK_NOT_FIND.getCode(), resultMap.get("message").toString());
        }
        String bank = resultMap.get("bank").toString();
        String cardType = resultMap.get("cardType").toString();
        String icon = resultMap.get("icon").toString();
        log.info(">>minjie 绑定银行卡信息：userId：{}，BizUserId：{}，phone：{}，cardNo：{}，name：{}，identityNo：{}",
                userId,yunStUser.getBizUserId(),phone,cardNo,name,identityNo);
        Map<String,String> map = yunBankCardService.applyBindBankCard(userId,yunStUser.getBizUserId(),phone,cardNo,bank,cardType,icon,name,identityNo);
        if (map.get("status").equals("error")) {
            return ResultBodyUtils.build(Integer.valueOf(map.get("code")), map.get("message"));
        }
        bandCardVO.setBank(bank);
        bandCardVO.setCardNo(cardNo);
        bandCardVO.setIcon(icon);
        bandCardVO.setIdentityNo(identityNo);
        bandCardVO.setName(name);
        bandCardVO.setType(cardType);
        bandCardVO.setPhone(phone);
        //是否进行电子签约，没有则进行
        if(yunStUser.getSignContract().equals(0)){
            Map<String,String> signMap = yunStUserService.signContract(yunStUser.getBizUserId());
            if(signMap.get("status").equals("OK")){
                bandCardVO.setIsSignContract(1);
            }else{
                bandCardVO.setIsSignContract(0);
            }
        }else {
            bandCardVO.setIsSignContract(1);
        }
        return ResultBodyUtils.ok(bandCardVO);
    }

    /**
     * 校验银行卡号信息
     * @param cardNo
     * @return
     */
    private  Map<String, Object> getCardNoInfo(String cardNo){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //获取该银行卡的类型
        HttpClient httpClient = new HttpClient();
        String url = validateAndCacheCardInfo+"?cardNo="+cardNo+"&cardBinCheck=true";
        String resultStr = httpClient.GET(url);
        //解析JOSN字符串
        JSONObject object = JSONObject.parseObject(resultStr);
        String validated = object.get("validated").toString();
        if(validated.equals("true")){
            String bankCode = object.getString("bank");
            String cardType = object.getString("cardType");
            //比对银行卡类型和银行名称
            QueryWrapper<YunBank> bankQueryWrapper = new QueryWrapper<YunBank>();
            bankQueryWrapper.eq("code",bankCode);
            YunBank yunBank = yunBankService.getOne(bankQueryWrapper);
            QueryWrapper<YunBankType> cardQueryWrapper = new QueryWrapper<YunBankType>();
            cardQueryWrapper.eq("card_type",cardType);
            YunBankType yunBankType = yunBankTypeService.getOne(cardQueryWrapper);
            if(yunBank==null){
                resultMap.put("status","error");
                resultMap.put("message","银行信息暂无记录");
                return resultMap;
            }
            if(yunBankType==null){
                resultMap.put("status","error");
                resultMap.put("message","银行卡类型暂无记录");
                return resultMap;
            }
            resultMap.put("status","OK");
            resultMap.put("bank",yunBank.getName());
            resultMap.put("cardType",yunBankType.getType());
            resultMap.put("icon",yunBank.getIcon());
            return resultMap;
        }else {
            resultMap.put("status","error");
            resultMap.put("message", "银行卡号查询不存在");
            return resultMap;
        }
    }
}
